const express = require("express");
const route = express.Router();
const path = require('path');
const fs = require('fs');
const advModel = require("../db/model/advModel") //引入数据库集合
const isLoginMiddle = require("../middleware/isLoginMiddle") //引入权限校验中间件


//删除管理员接口
route.delete("/deleteAdv", isLoginMiddle, async (req, res) => {

    //取出图片的id
    const {
        _id
    } = req.query

    //删除文件中对应的图片
    try {
        //首先去数据库查询当前的_id对应的图片名
        const {
            advHref
        } = await advModel.findOne({
            _id
        })

        const imgName = advHref.split("/")[2];

        //删除这个图片
        fs.unlink(path.resolve(__dirname, "../upload", imgName), () => {
            console.log("删除图片成功");
        })

    } catch (e) {
        console.log("删除图片逻辑有错" + e.message);
        return res.send({
            code: 10001,
            msg: "删除图片逻辑有错" + e.message,
            data: null
        })
    }


    //删除数据库的数据
    try {
        const deleteResult = await advModel.deleteOne({
            _id
        })
        res.send({
            code: 10000,
            msg: "删除广告列表成功",
            data: null
        })

    } catch (e) {
        console.log("删除广告列表失败" + e.message);
        res.send({
            code: 10001,
            msg: "删除广告列表失败" + e.message,
            data: null
        })
    }


})

module.exports = route;